<template>
  <div class="goods">
    <div class="topNav">
      <van-nav-bar
        title="商品详情"
        left-text="返回"
        left-arrow
        @click-left="quit"
      />
    </div>
    <div class="content">
      <div class="good">
        <img class="big" :src="itemData.large_img" />
        <div class="content1">
          <div class="title">
            <h2>{{ itemData.name }}</h2>
            <p>{{ itemData.enname }}</p>
            <span>&yen;{{ itemData.price }}</span>
          </div>
          <div class="choose">
            <p v-for="(item1, index1) in itemData.rules" :key="index1">
              <span>{{ item1.title }}</span>
              <button
                v-for="(item2, index2) in item1.subRule"
                :key="index2"
                :class="{ active: item1.activeIndex === index2 }"
                @click="choose(item1, index2)"
              >
                {{ item2.title }}
              </button>
            </p>
          </div>
          <div class="num">
            <span>选择数量</span>
            <div class="choosenum">
              <van-stepper
                v-model="num"
                theme="round"
                button-size="22"
                disable-input
              />
            </div>
          </div>
          <div class="mianshu">
            <h3>商品描述</h3>
            <p v-for="(item, index) in itemData.desc" :key="index">
              {{ index + 1 }}.{{ item }}
            </p>
          </div>
        </div>
      </div>
    </div>
    <div class="footer">
      <van-goods-action>
        <van-goods-action-icon
          @click="go('Shopbag')"
          icon="cart-o"
          text="购物袋"
          :badge="$root.publicShopbagCount - 0"
        />
        <van-goods-action-icon
          :icon="isLike ? 'like' : 'like-o'"
          :text="isLike ? '已收藏' : '收藏'"
          @click="like"
        />
        <van-goods-action-button
          color="rgb(106,145,236)"
          type="warning"
          text="加入购物车"
          @click="addShop"
        />
        <van-goods-action-button
          color="rgb(12,52,186)"
          type="danger"
          text="立即购买"
          
        />
      </van-goods-action>
    </div>
  </div>
</template>

<script>
export default {
  name: "Goods",
  data() {
    return {
      num: 1,
      selected: 0,
      selected1: 0,
      item: "",
      itemData: [],
      isLike: false,
      countall: "",
      pid: "",
      oneSid: "",
    };
  },
  methods: {
    // 返回上一级
    quit() {
      this.$router.go(-1);
    },
    // 页面跳转
    go(name) {
      this.$router.push({ name });
    },
    // 数值增加
    addNum() {
      this.num++;
      if (this.num >= 99) {
        this.num = 99;
      }
    },
    // 数值减少
    jianNum() {
      this.num--;
      if (this.num <= 1) {
        this.num = 1;
      }
    },
    // 选择激活下标
    choose: function (v1, index) {
      v1.activeIndex = index;
    },
    // 获取产品详情
    getTypeData(pid) {
      this.axios({
        methods: "GET",
        url: "/productDetail",
        params: {
          pid,
        },
      })
        .then((res) => {
          if (res.data.code === 600) {
            // 处理商品描述
            let data = res.data.result[0];
            data.desc = data.desc.split(/\n/);

            let rules = ["cream", "milk", "sugar", "tem"];
            let rulesData = [];
            rules.forEach((v) => {
              // 排除空规格
              if (!data[v]) {
                return;
              }

              let rule = {
                title: data[`${v}_desc`],
                activeIndex: 0,
                subRule: [],
              };

              let subRuleData = data[v].split(/\//);
              subRuleData.forEach((item) => {
                rule.subRule.push({ title: item });
              });

              rulesData.push(rule);
            });

            data.rules = rulesData;

            this.itemData = data;
          }
        })
        .catch((err) => {
          
        });
    },
    // 添加收藏
    like() {
      let url = "";

      if (this.isLike) {
        url = "/notlike";
      } else {
        url = "/like";
      }
      // 获取token
      let token = this.$cookies.get("TOKEN");
      this.axios({
        method: "POST",
        url,
        data: {
          pid: this.pid,
          tokenString: token,
        },
      })
        .then((res) => {
          this.$toast(res.data.msg);
          if (res.data.code == 700) {
            //用户未登录, 拦截操作, 通知用户去登录
            this.$toast("请先登录");
            setTimeout(() => {
              this.$router.push({ name: "Login" });
            }, 2000);
            return;
          }
          if (res.data.code === 800) {
            //收藏商品
            this.isLike = true;
          } else if (res.data.code === 900 && res.data.result === 1) {
            //取消收藏商品
            this.isLike = false;
          }
        })
        .catch((err) => {
          
        });
    },
    // 判断收藏
    findLike() {
      let token = this.$cookies.get("TOKEN");

      this.axios({
        method: "GET",
        url: "/findlike",
        params: {
          pid: this.pid,
          tokenString: token,
        },
      })
        .then((res) => {
          // 
          if (res.data.code === 1000 && res.data.result.length === 1) {
            //当前商品已经被用户收藏
            this.isLike = true;
          }
        })
        .catch((err) => {
          
        });
    },
    // 切换状态
    toggle(index) {
      this[index] = !this[index];
    },
    // 查询商品数量
    goodsCheck() {
      let token = this.$cookies.get("TOKEN");

      this.axios({
        method: "GET",
        url: "/shopcartCount",
        params: {
          tokenString: token,
        },
      })
        .then((res) => {
          if (res.data.code === 4000) {
            this.$root.publicShopbagCount = res.data.result - 0;
          }
        })
        .catch((err) => {
          
        });
    },
    // 添加商品进入购物车
    addShop() {
      let rules = this.itemData.rules;
      let selectRule = [];

      rules.forEach((v) => {
        selectRule.push(v.subRule[v.activeIndex].title);
      });

      let token = this.$cookies.get("TOKEN");
      this.axios({
        method: "POST",
        url: "/addShopcart",
        data: {
          tokenString: token,
          pid: this.pid,
          rule: selectRule.join("/"),
          count: this.num,
        },
      })
        .then((res) => {
          if (res.data.code === 3000) {
            this.$toast(res.data.msg);
            this.$root.publicShopbagCount += this.num - 0;
          }
        })
        .catch((err) => {
          
        });
    },
    // 立即购买
    buyGood() {
      // this.$router.push({name:"Order" , query:this.pid})
      
      let rules = this.itemData.rules;
      let selectRule = [];

      rules.forEach((v) => {
        selectRule.push(v.subRule[v.activeIndex].title);
      });

      let token = this.$cookies.get("TOKEN");
      this.axios({
        method: "POST",
        url: "/addShopcart",
        data: {
          tokenString: token,
          pid: this.pid,
          rule: selectRule.join("/"),
          count: this.num,
        },
      })
        .then((res) => {
            this.oneSid = res.data.sid;
          this.$router.push({name:"Order" , query:{sids:this.oneSid}})
        })
        .catch((err) => {
          
        });
    },
  },
  created() {
    this.pid = this.$route.query.item;
    this.getTypeData(this.$route.query.item);
    this.findLike();
    this.goodsCheck();
    if (this.$root.publicShopbagCount === "") {
      this.goodsCheck();
    }
  },
};
</script>

<style lang="less" scoped>
* {
  margin: 0;
  padding: 0;
}
.good {
  overflow-y: auto;
  background-color: rgb(247, 247, 247);
}
.big {
  width: 100%;
}
.topNav {
  position: sticky;
  top: 0;
}
.content {
  position: fixed;
  top: 46px;
  bottom: 40px;
  overflow-y: auto;
}
.content1 {
  margin: 0 15px;
  padding: 15px;
  background-color: white;
  box-sizing: border-box;
  position: relative;
  top: -30px;
  border-radius: 10px;
  .title {
    margin-bottom: 20px;
    h2 {
      margin-bottom: 10px;
    }
    p {
      font-size: 14px;
    }
    span {
      font-size: 16px;
      font-weight: bold;
      color: rgb(12, 52, 186);
      position: absolute;
      right: 20px;
      top: 20px;
    }
  }
  .choose {
    font-size: 14px;
    margin-bottom: 20px;
    p {
      margin-bottom: 10px;
    }
    span {
      display: inline-block;
      width: 60px;
    }
    button {
      width: 60px;
      height: 30px;
      border-radius: 15px;
      border: none;
      line-height: 30px;
      text-align: center;
      margin: 0 10px;
      font-size: 12px;
    }
    .active {
      background-color: rgb(12, 52, 186);
      color: white;
    }
  }
  .num {
    padding: 20px 0;
    border-top: 1px solid rgba(39, 39, 39, 0.3);
    border-bottom: 1px solid rgba(39, 39, 39, 0.3);
    position: relative;
    span {
      font-size: 14px;
      display: inline-block;
      width: 60px;
      margin-bottom: 5px;
    }
    .choosenum {
      display: inline-block;
      position: absolute;
      right: 0px;
      top: 20px;
      display: flex;
      /deep/ .van-stepper--round .van-stepper__plus {
        background-color: #0c34ba;
      }

      /deep/ .van-stepper--round .van-stepper__minus {
        color: #0c34ba;
        border-color: #0c34ba;
      }
    }
  }
  .mianshu {
    margin-top: 5px;
    // margin-bottom: 20px;
    font-size: 12px;
    color: gray;
    h3 {
      padding: 10px 0;
      color: #000;
      font-weight: normal;
    }
    p {
      line-height: 20px;
    }
  }
}
</style>